package com.jxit0573.android.lib.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;

import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

/**
 * @author jia
 */
public class X5WebView extends WebView {

    public OnWebViewCallback callback;
    private Context context;

    @SuppressLint("SetJavaScriptEnabled")
    public X5WebView(Context context) {
        super(context);
        this.context = context;
        setBackgroundColor(Color.WHITE);
        this.setWebViewClient(new WebViewClient() {
            /**
             * 防止加载网页时调起系统浏览器
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                } else {
                    view.loadUrl(url);
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (callback != null) {
                    callback.onUrlCallback(url);
                }
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                sslErrorHandler.proceed();
            }
        });
        this.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                if (callback != null) {
                    callback.openFileChooser(uploadMsg);
                }
                openFileChooseProcess();
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                if (callback != null) {
                    callback.openFileChooser(uploadMsg);
                }
                openFileChooseProcess();
            }

            // For Android  > 4.1.1
            @Override
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                if (callback != null) {
                    callback.openFileChooser(uploadMsg);
                }
                openFileChooseProcess();
            }

            // For Android  >= 5.0
            @Override
            public boolean onShowFileChooser(com.tencent.smtt.sdk.WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                if (callback != null) {
                    callback.onShowFileChooser(filePathCallback);
                }
                openFileChooseProcess();
                return true;
            }
        });
        initWebSettings();
        setInitialScale(5);
    }

    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
//        startActivityForResult(Intent.createChooser(i, "test"), 0);
    }

    private void initWebSettings() {
        WebSettings webSettings = this.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setSupportMultipleWindows(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDatabasePath(context.getDir("x5_db", Context.MODE_PRIVATE).getPath());
        webSettings.setAppCacheEnabled(true);
        webSettings.setAppCachePath(context.getDir("x5_cache", Context.MODE_PRIVATE).getPath());
        webSettings.setAppCacheMaxSize(Long.MAX_VALUE);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setPluginState(WebSettings.PluginState.ON_DEMAND);
        setWebContentsDebuggingEnabled(true);
    }

    public void setUserAgent(String userAgent) {
        getSettings().setUserAgentString(getSettings().getUserAgentString() + userAgent);
    }

    public void setBuiltInZoomControls() {
        this.getSettings().setBuiltInZoomControls(true);
    }

    public void setCallback(OnWebViewCallback callback) {
        this.callback = callback;
    }

    public interface OnWebViewCallback {
        /**
         * H5页面当前url
         *
         * @param url 当前url
         */
        void onUrlCallback(String url);

        /**
         * 接收回调
         *
         * @param uploadMsg 回调
         */
        void openFileChooser(ValueCallback<Uri> uploadMsg);

        /**
         * 接收回调
         *
         * @param uploadMsg 回调
         */
        void onShowFileChooser(ValueCallback<Uri[]> uploadMsg);

        /**
         * 当前H5页面标题
         *
         * @param title 标题
         */
        void onReceivedTitle(String title);
    }
}
